package com.zyl.Ecs.realtime.config;

import com.zyl.Ecs.common.response.Result;
import com.zyl.Ecs.common.response.ResultCode;
import com.zyl.Ecs.common.utils.CUtil;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import java.util.Timer;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @version v1.0
 * @ProjectName: Ecs
 * @Package: com.zyl.Ecs.realtime.config
 * @ClassName: AbstractBaseWebSocket
 * @Description TODO
 * @Author 翟玉龙
 * @Date 2024/12/6-17:02
 */
@Component
public abstract class AbstractBaseWebSocket {

    protected Session session;

    protected final Timer timer = new Timer();

    protected boolean run = true;

    /**
     * 保存所有会话对象（暂时只用于统计同时连接数）
     */
    protected static final CopyOnWriteArraySet<AbstractBaseWebSocket> webSocketSet = new CopyOnWriteArraySet<>();


    /**
     * 客户端发来消息（暂时不用）
     *
     * @param message 消息
     */
    @OnMessage
    public void onMessage(String message) {
        CUtil.logInfo(
                String.format(
                        "[websocket] 收到客户端发来的消息：%s",
                        message
                )
        );
    }

    /**
     * 客户端断开连接
     *
     * @param session 会话对象
     */
    @OnClose
    public void onClose(Session session) {
        this.session = session;
        webSocketSet.remove(this);
        CUtil.logInfo(
                String.format(
                        "[websocket] 连接断开 总数：%d",
                        webSocketSet.size()
                )
        );
        //run = false;
        timer.cancel();
    }

    public void sendError() {
        try {
            session.getBasicRemote().sendObject(Result.error(ResultCode.FAILURE));
        } catch (Exception e) {
            CUtil.logInfo("Socket通信出现错误：" + e);
        }
    }

}